//
//  XLComposeViewController.swift
//  XLVeibo
//
//  Created by macbook on 16/7/3.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit
import SVProgressHUD

class XLComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    
   
 var response: (AnyObject)?
    func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        
        setItems()
        
        //添加
        view.addSubview(composeTextView)
        view.addSubview(composeToolbar)
        composeTextView.addSubview(composePicture)
        
        composeTextView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }

        
        composeToolbar.snp_makeConstraints { (make) in
            
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(54)
        }
        composeTextView.backgroundColor = UIColor.whiteColor()
        composePicture.snp_makeConstraints { (make) in
            
            make.left.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: KScreenW - 20, height: KScreenW - 20))
        }
        
        //弹出键盘
        composePicture.composePictureViewClosure = {[weak self]()->() in
        
            self?.selectImage()
        
        }
        
        //监听toolbar 按钮点击的那个
        composeToolbar.colose = {[weak self] (type:composeToolbarType)->()in
            
            switch type {
            case .Picture:
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
                self?.emotionKeyBoard()
            case .Add:
                print("+")

            }
        }
        
        //接受表情键盘删除通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XLComposeViewController.deleteButtonClick), name: EmoticonDeleteNoti, object: nil)
       
        //接受表情按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XLComposeViewController.emoticonButtonClick(_:)), name: EmoticonButtonNoti, object: nil)
        
        
        //通过系统方法监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XLComposeViewController.KeyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    
    //删除按钮通知
    func deleteButtonClick(){
    
        composeTextView.deleteBackward()
    }
    
    //接受表情按钮
    func emoticonButtonClick(noti: NSNotification){
        
        guard let emoticon = noti.object as?XLEmoticon else{
        
            return
        }
        
        //emoji表情
        if emoticon.isEmoji {
            
            composeTextView.insertText(((emoticon.code ?? "")as NSString).emoji())
        }else{
        
            //记录conpsetTextView上一次富文本信息
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            //图片表情 文本附件
            let att = XLTextAttachment()
            
            //设置emoticon
            att.emoticon = emoticon
            //设置image
            let path = emoticon.path ?? ""
            let png = emoticon.png ?? ""
            let name = path + png
            att.image = UIImage(named: name,inBundle: XLEmoticonShardTools.shardTools.emoticonBundle,compatibleWithTraitCollection: nil)
            
            //行高
            let lineHight = composeTextView.font!.lineHeight
            
            //设置bouns
            att.bounds = CGRect(x: 0, y: -4, width: lineHight, height: lineHight)
            
            //创建一个不可变富文本
            let attr = NSAttributedString(attachment: att)
            
            //获取选中的光标
            let selectRange = composeTextView.selectedRange
            
            //替换
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            //设置副文本字体
            oldAttr.addAttributes([NSFontAttributeName:composeTextView.font!], range: NSRange(location: 0, length: oldAttr.length))
            composeTextView.attributedText = oldAttr
            
            //更改composeText光标
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            //发送一个通知 影藏或者显示textView的站位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            //掉用代理方法使右侧按钮改变状态
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
        }
     
    }
    
    //监听frame的值的改变
    func KeyboardWillChange(noti:NSNotification){
    
        //NSRcte mac开发中用的 我们移动端开发用CGRect 需要我们先把NSRect  先转换成NSValue
        
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        //更新约束
        composeToolbar.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(rect.origin.y - KScreenH)
        }
        
        UIView.animateWithDuration(0.25) { 
            
            self.view.layoutIfNeeded()
        }
     }
    
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //设置item
    func setItems(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(XLComposeViewController.canseClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(XLComposeViewController.sendClick))
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }
    
    //取消按钮的实现
    func canseClick(){
    
        self.dismissViewControllerAnimated(false, completion: nil)
        composeTextView.resignFirstResponder()
    }
    
    //发送按钮的实现
    func sendClick(){
       
        if composePicture.imageList.count > 0 {
            
            sendeMessageWithPicture()
            canseClick()
        }else{
             update()
            canseClick()
        
        }
    
    }
    
    
    //懒加载 nac中间显示
    private lazy var titleView:UILabel = {
    
        let label = UILabel()
        let name = XLUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        //最终显示的文字
        let str = "发微博\n\(name)"
        
        //富文本
        let attr = NSMutableAttributedString(string: str)
        //获取range 先转换成oc的NSString
        let range = (str as NSString).rangeOfString(name)
        //设置富文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(13)], range: range)
       
        label.attributedText = attr
        label.textAlignment = .Center
        label.numberOfLines = 0
        
        //设置大小
        label.sizeToFit()
        return label
    }()
    
    //toolbar
    private lazy var composeToolbar:XLComposeToolbar = XLComposeToolbar()
    
    //textView
    private lazy var composeTextView:XLComposeTextView = {
    
        let view = XLComposeTextView()
        view.placeolder = "微博内容,不超过140字"
        view.font = UIFont.systemFontOfSize(28)
        
        //使textView可以上下移动
        view.alwaysBounceVertical = true
        
        //设置代理用来监听文字变化，
        view.delegate = self
         return view
    }()
    
    //picture
    private lazy var composePicture:XLComposePictureViw = XLComposePictureViw()
    
    //自定义表情键盘
    private lazy var keyBoard:XLEmotionKeyBoard = {
    
        let view = XLEmotionKeyBoard()
        
        view.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 216)
        return view
    }()
}



extension XLComposeViewController:UITextViewDelegate{

    //监听文字的变化
    func textViewDidChange(textView: UITextView) {
        
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //拖动取消键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        composeTextView.resignFirstResponder()
    }
    
}

//发送微博请求
extension XLComposeViewController{

    func update(){
    
        XLNetworkTools.sharedTools.composeSendMessage(composeTextView.text, success: { (response) in
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
         
        }) { (error) in
           
            SVProgressHUD.showErrorWithStatus("发送失败")
        }
    }
    
    
    //发布带图片的微博，只允许我们发布一张图
    func sendeMessageWithPicture (){
     
        XLNetworkTools.sharedTools.sendeMessageWithPicture(composeTextView.text, imageList: composePicture.imageList, success: { (response) in
     

            SVProgressHUD.showSuccessWithStatus("发送成功")
            self.response = response
          
         }) { (error) in
             
            SVProgressHUD.showErrorWithStatus("发送失败")
                
        }
    }
}

// MARK: - 处理tool点击事件f
extension XLComposeViewController{
    
    func selectImage(){
    
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        //打开相册
        presentViewController(picker, animated: true, completion: nil)
    }
    
    //切换键盘
    func emotionKeyBoard(){
        
        //系统键盘
        if composeTextView.inputView == nil {
            
            //换成自定义键盘
            composeTextView.inputView = keyBoard
            
            //键盘样式
            composeToolbar.isEmoticon = true
            
            
        }else
        {    //代表自定义键盘
            //切换成系统键盘
            composeTextView.inputView = nil
            composeToolbar.isEmoticon = false
        }
        
        //刷新
        composeTextView.reloadInputViews()
        //成为第一响应
        composeTextView.becomeFirstResponder()
    }

}

// MARK: - 打开相册的代理方法
extension XLComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        
        //填充图片
        
        composePicture.addImage(scaleImageOfWith(600, image: image))
        //如果实现代理
        picker.dismissViewControllerAnimated(false, completion: nil)
    }
    
    //压缩图片
    func scaleImageOfWith(with:CGFloat,image:UIImage)->UIImage{
    
        //如果传入的图片小于我们设置定的比例，直接返回
        if with > image.size.width {
            
            return image
        }
        
        //等比例计算图片高度
        let hight = (with * image.size.height) / image.size.width
        
        //创建一rect
        let rect = CGRect(x: 0, y: 0, width: with, height: hight)
        
        //开启上下文
        UIGraphicsBeginImageContext(rect.size)
        
        
        //将image渲染到上下文中
        image.drawInRect(rect)
        
        //获取上下文结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图形上下文
        UIGraphicsEndImageContext()
        
        return result
    
    }
    
    
}





